package jp.co.ricoh.melody.views.activities;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.databinding.DataBindingUtil;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import jp.co.ricoh.melody.R;
import jp.co.ricoh.melody.application.BaseApplication;
import jp.co.ricoh.melody.application.SmartSDKApplication;
import jp.co.ricoh.melody.databases.DBManager;
import jp.co.ricoh.melody.databinding.MainActivityBinding;
import jp.co.ricoh.melody.presenters.IMainActivityPresenter;
import jp.co.ricoh.melody.presenters.MainActivityPresenter;
import jp.co.ricoh.melody.utils.ConstantUtils;
import jp.co.ricoh.melody.views.fragments.AlarmListFragment;
import jp.co.ricoh.melody.views.fragments.CommonDialogFragment;
import jp.co.ricoh.melody.views.fragments.ProgressDialogFragment;

/**
 * Copyright (C) 2016 RICOH Co.,LTD.
 * All rights reserved.
 */
public class MainActivity extends BaseActivity
        implements IMainActivityView, CommonDialogFragment.OnCommonDialogButtonClickListener {
    public static SmartSDKApplication app;
    public static BaseApplication mapp;
    private static final int HIDE_ADD_BUTTON_DURATION = 300;
    private MainActivityBinding mBinding;
    private IMainActivityPresenter mMainActivityPresenter;
    private boolean mIsAddAlarmStarted = false;
    private CommonDialogFragment mCommonDialogFragment;
    private ProgressDialogFragment mProgressDialogFragment;
    private boolean mIsFirstAdd;
    private BaseApplication application;
    private BroadcastReceiver mHomeKeyEventReceiver;





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        setSupportActionBar(mBinding.toolbar);
        mapp=BaseApplication.getInstance();
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            //noinspection deprecation
            actionBar.setTitle(ConstantUtils.SPACE_STRING + getString(R.string.app_name));
            actionBar.setIcon(getResources().getDrawable(R.drawable.logo__melody));
        }

        initView();
//        if (!DBManager.getInstance().isDataLoaded()) {
//            loadDataFromHDD();
//        } else {
//            initView();
//        }


//          mHomeKeyEventReceiver = new BroadcastReceiver() {
//            String SYSTEM_REASON = "reason";
//            String SYSTEM_HOME_KEY = "homekey";
//            @Override
//            public void onReceive(Context context, Intent intent) {
//                String action = intent.getAction();
//                if(action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)){
//                    String reason = intent.getStringExtra(SYSTEM_REASON);
//                    if(TextUtils.equals(reason, SYSTEM_HOME_KEY)){
//                        Log.i("home123","home123");
//                    }
//                }
//            }
//        };
//        registerReceiver(mHomeKeyEventReceiver, new IntentFilter(
//                Intent.ACTION_CLOSE_SYSTEM_DIALOGS));



    }

    private void loadDataFromHDD() {
        showProgressDialog(getString(R.string.progress_dialog_msg_load));
        DBManager.getInstance().loadData(new DBManager.OnDataLoadedListener() {
            @Override
            public void onDataLoaded(boolean isHddReady) {
                dismissProgressDialog();
                if (isHddReady) {
                    initView();
                } else {
                    showHDDErrorDialog();
                }
            }
        });
    }

    private void initView() {
        mMainActivityPresenter = new MainActivityPresenter();
        mMainActivityPresenter.onCreateView(this);

        mIsFirstAdd = mMainActivityPresenter.isFirstAdd();
        mMainActivityPresenter.updateAddButtonGuideVisibility(mIsFirstAdd);

        mBinding.addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mIsFirstAdd) {
                    mMainActivityPresenter.setFirstAdd();
                    mIsFirstAdd = false;
                    mMainActivityPresenter.updateAddButtonGuideVisibility(mIsFirstAdd);
                }

                mMainActivityPresenter.transitToAddAlarmScreen();
            }
        });

        AlarmListFragment alarmListFragment = AlarmListFragment.newInstance();
        alarmListFragment.setOnAlarmListScrollListener(new AlarmListFragment.OnAlarmListScrollListener() {
            @Override
            public void onStateChanged(boolean scrolling) {
                float scale = scrolling ? 0 : 1;
                ViewCompat.animate(mBinding.addBtn)
                        .scaleY(scale)
                        .scaleX(scale)
                        .setDuration(HIDE_ADD_BUTTON_DURATION)
                        .start();
            }
        });
        alarmListFragment.setRecycleView(mBinding.recycleBinContainer, mBinding.recycleBinImg);

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.alarmListContentFrame, alarmListFragment);
        ft.commitAllowingStateLoss();
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public void showMessageAlarmSizeHasReachMax() {
        mCommonDialogFragment = CommonDialogFragment.newInstance(getResources().getString(R.string.alarm_size_reach_max), null, null, getResources().getString(R.string.btn_ok));
        mCommonDialogFragment.setOnCommonDialogButtonClickListener(this);
        mCommonDialogFragment.show(getFragmentManager(), null);
    }

    @Override
    public void onBackPressed() {
    }

    @Override
    public void setAddButtonGuideVisibility(int visibility) {
        mBinding.layoutAddButtonGuide.setVisibility(visibility);

    }

    @Override
    public void navigateToAddAlarmActivity() {
        if (mIsAddAlarmStarted) {
            return;
        }
        mIsAddAlarmStarted = true;
        Intent intent = new Intent(this, AddAlarmActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        startActivity(intent);
    }

    @Override
    public void transitToNoteListActivity() {
        Intent intent = new Intent(this, NoteListActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mIsAddAlarmStarted = false;
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public void onButtonClicked(CommonDialogFragment.ButtonType type) {
        switch (type) {
            case RIGHT:
                if (mCommonDialogFragment != null) {
                    mCommonDialogFragment.dismissAllowingStateLoss();
                }
                break;
            default:
                break;
        }
    }

    public void showProgressDialog(String msg) {
        mProgressDialogFragment = ProgressDialogFragment.newInstance(msg);
        mProgressDialogFragment.show(getFragmentManager(), null);
    }

    public void dismissProgressDialog() {
        if (mProgressDialogFragment != null) {
            mProgressDialogFragment.dismissAllowingStateLoss();
        }
    }

    private void showHDDErrorDialog() {
        final CommonDialogFragment commonDialogFragment = CommonDialogFragment.newInstance(getString(R.string.hdd_error_msg), null, null, getString(R.string.btn_ok));
        commonDialogFragment.setOnCommonDialogButtonClickListener(new CommonDialogFragment.OnCommonDialogButtonClickListener() {
            @Override
            public void onButtonClicked(CommonDialogFragment.ButtonType type) {
                commonDialogFragment.dismissAllowingStateLoss();
                MainActivity.this.finish();
            }
        });
        commonDialogFragment.setCancelable(false);
        commonDialogFragment.show(getFragmentManager(), null);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId()==R.id.menu_note){
            mMainActivityPresenter.transitToMpteListScreen();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
